import 'package:flutter/material.dart';
import 'package:poet/api/poet.dart';
import 'package:poet/pages/search_page/components/item_group.dart';
import 'package:poet/pages/search_page/components/search_input_widget.dart';
import 'package:poet/pages/search_page/poet_page.dart';

class SearchPage extends StatefulWidget {
  SearchPage({Key key}) : super(key: key);

  @override
  _SearchPage createState() {
    return new _SearchPage();
  }
}

class _SearchPage extends State<SearchPage>
    with SingleTickerProviderStateMixin {
  final _authors =
      '李白,白居易,杜甫,苏轼,辛弃疾,李清照,刘禹锡,王维,李商隐,纳兰性德,杜牧,陆游,陶渊明,孟浩然,元稹,李煜,柳宗元,岑参,韩愈,王安石,欧阳修,齐己,贾岛,韦应物,曹操,温庭筠,柳永,刘长卿,李贺,曹植,王昌龄,张籍,孟郊,皎然,贯休,许浑,罗隐,杨万里,陆龟蒙';
  final _dynasty = '唐,宋,元,明,清';
  final _genre = '诗,词,文';
  final _collection = '唐诗三百,诗经,楚辞';

  String _results = "";

  void onItemTap(index) {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => PoetPage()),
    );
  }

  Widget buildResult() {
    var split = this._results.split(",");
    var textStyle = TextStyle(fontFamily: 'hyqts', fontSize: 16);
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 0, horizontal: 16),
      child: ListView.separated(
        itemCount: split.length,
        itemBuilder: (BuildContext context, int index) {
          return GestureDetector(
            onTap: () => {onItemTap(index)},
            child: ListTile(
              title: Text(
                "${split[index]}",
                style: textStyle,
              ),
            ),
          );
        },
        separatorBuilder: (BuildContext context, int index) {
          return Divider();
        },
      ),
    );
  }

  @override
  void initState() {
    super.initState();
  }

  void _onTypeChange(String type) {
    setState(() {
      if (type == "作者") {
        this._results = _authors;
      } else if (type == "朝代") {
        this._results = _dynasty;
      } else if (type == "类型") {
        this._results = _genre;
      } else {
        this._results = "";
        getAllPoet();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final _searchTypes = ["全部", "作者", "朝代", "类型"];
    return Scaffold(
      appBar: AppBar(
        title: SearchBar(),
        automaticallyImplyLeading: false,
      ),
      body: Column(
        children: <Widget>[
          ItemGroup(
            onItemChange: _onTypeChange,
            items: _searchTypes,
          ),
          Expanded(
            child: buildResult(),
          )
        ],
      ),
    );
  }
}
